# -*- coding: UTF-8 _*_


import pytest
from selenium import webdriver as wd
import uiautomator2 as u2
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from common import appbase
from common.appbase import APPBase
from common.mylog import GeneralLogger
from page.web.loginpage import *
from loguru import logger
from common.readconfig import ReadConfig
from config.config import base_path

FFoption = wd.FirefoxOptions()
FFoption.binary_location = r'C:/Program Files/Mozilla Firefox/firefox.exe'
FFdriverService = Service('C:/Program Files/Mozilla Firefox/geckodriver.exe')

device = ReadConfig.parse_yaml(filename='config/appconfig.yaml', key='base.device')
appname = ReadConfig.parse_yaml(filename='config/appconfig.yaml', key='base.appname')

app_jpg_path = base_path + ReadConfig.parse_yaml(filename='config/appconfig.yaml', key='path.jpg')
app_log_path = base_path + ReadConfig.parse_yaml(filename='config/appconfig.yaml', key='path.log')

web_jpg_path = base_path + ReadConfig.parse_yaml(filename='config/webconfig.yaml', key='path.jpg')
web_log_path = base_path + ReadConfig.parse_yaml(filename='config/webconfig.yaml', key='path.log')
now = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
# logger=GeneralLogger().returnlogger()
FF=None
chrome=None
AppDrives=None

def pytest_addoption(parser):
    parser.addoption('--case_type', action='store', default='web', help='case_type option:web or app')
    parser.addoption('--browser', action='store', default='', help='browser option:firefox or chrome')


@pytest.fixture(scope='session')
def mydriver(request):
    name = request.config.getoption('--browser')
    case_type = request.config.getoption('--case_type')
    global FF,chrome,AppDrives
    if case_type.lower() == 'web':
        logger.add(web_log_path + now + '_all.log', rotation="00:00", encoding='utf-8')
        if name.lower() == 'firefox':
            FF = wd.Firefox(service=FFdriverService, options=FFoption)
            logger.error('正在启动浏览器：' + name.lower())
            yield FF
        elif name.lower() == 'chrome':
            chrome = wd.Chrome()
            # brower.get_screenshot_as_png()
            logger.error('正在启动浏览器：' + name.lower())
            yield chrome
        else:
            chrome = wd.Chrome()
            logger.error('正在启动浏览器：CHROME')
    elif case_type.lower() == 'app':
        # logger.add(app_log_path + now + '_all.log', rotation="00:00", encoding='utf-8')
        AppDrives = u2.connect_usb(device)
        logger.info('正在启动设备：' + device)
        AppDrives.app_start(appname, stop=True)
        logger.info('正在启动应用：' + appname)
        yield AppDrives
    def end():
        if case_type.lower() == 'web':
            if name.lower() == 'firefox':
                logger.error('用例结束后，关闭浏览器:' + name)
                FF.quit()
            elif name.lower() == 'chrome':
                logger.error('用例结束后，关闭浏览器:' + name)
                chrome.quit()
        elif case_type.lower() == 'app':
            AppDrives.app_stop(appname)
            logger.info('用例结束后，关闭应用')

    request.addfinalizer(end)  # 终结函数
    # return brower


# 所有用例先登录
@pytest.fixture(scope='session', name='login1')
def my_login(mydriver):
    web = loginpage()
    web.login(mydriver)


# 出错自动截图
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    print(rep)
    if rep.when == "call" and rep.failed:
        if hasattr(FF, "get_screenshot_as_png"):
            try:
                WebDriverWait(FF, 10).until(EC.alert_is_present())
                # 出错时，页面可能出现告警框，先确认，才能截图
                FF.switch_to.alert.accept()
                allure.attach(FF.get_screenshot_as_png(), "异常截图", allure.attachment_type.PNG)
                logger.warning('当前用例执行失败，FF进行关键截图')
            except:
                allure.attach(FF.get_screenshot_as_png(), "异常截图", allure.attachment_type.PNG)
                logger.warning('当前用例执行失败，FF进行关键截图')
        elif hasattr(chrome, "get_screenshot_as_png"):
            try:
                WebDriverWait(chrome, 10).until(EC.alert_is_present())
                # 出错时，页面可能出现告警框，先确认，才能截图
                chrome.switch_to.alert.accept()
                allure.attach(chrome.get_screenshot_as_png(), "异常截图", allure.attachment_type.PNG)
                logger.warning('当前用例执行失败，chrome进行关键截图')
            except:
                allure.attach(FF.get_screenshot_as_png(), "异常截图", allure.attachment_type.PNG)
                logger.warning('当前用例执行失败，chrome进行关键截图')
        elif hasattr(AppDrives,'screenshot'):
            APPBase.save_myscreenshot(driver=AppDrives,pagename='')
            logger.warning('当前用例执行失败，进行关键截图')

# 控制台输出中文
def pytest_collection_modifyitems(items):
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")
